home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 3897 < prev    next >
Encoding:
Text File  |  1996-08-06  |  1.9 KB  |  73 lines

  1. Path: netnews.whoi.edu!NewsWatcher!user
  2. From: davef@mbl.edu (Dave Fernandes)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: [Q] equivalent or better strtok() in C++?
  5. Date: Fri, 26 Jan 1996 12:05:17 -0500
  6. Organization: Marine Biological Laboratory
  7. Message-ID: <davef-2601961205170001@128.128.173.90>
  8. References: <4e6p1m$anc@walrus2.walrus.com>
  9. NNTP-Posting-Host: 128.128.173.90
  10.  
  11. In article <4e6p1m$anc@walrus2.walrus.com>, fjordao@walrus.com (Felipe
  12. Jordao) wrote:
  13.  
  14. > Hi,
  15. > I have been trying to use strtok() to get tokens from a delimited
  16. > string but it only recognizes tokens with one or more characters.  (I
  17. > know this is how the function is defined).
  18. > However...
  19.  
  20.  
  21. I don't know of any pretty way to do this, but I use the following
  22. function.  It uses the ANSI <string> class.
  23.  
  24. Arguments:
  25. line     - the input string
  26. delimit  - the char* used to delimit the text (Ex: char *delimit = ".")
  27. array    - the output array of strings
  28.            If you want to get a char* from this, use:
  29.                   char *arrayElement_i = array[i].c_str();
  30. n_max    - the size of array[].  This is the maximum number of items that will
  31.            be scanned in.
  32.  
  33. The function returns the number of items that were actually scanned in.
  34.  
  35. Hope this helps.
  36.       Dave
  37.  
  38. //____________________________________________________________________________
  39.  
  40. #include <string>
  41.  
  42. int StringScan(const string &line, const char *delimit, string array[],
  43.    int n_max)
  44. {
  45.    const string delimiter(delimit);
  46.    size_t len = line.length();
  47.    size_t start = 0;
  48.    int nFound = 0;
  49.    
  50.    while (nFound < n_max) {
  51.       size_t end = line.find_first_of(delimiter, start);
  52.       if (end > len) end = len;
  53.       
  54.       if (end < start)
  55.          break;
  56.       else if (end > start)
  57.          array[nFound++] = line.substr(start, end-start);
  58.       else
  59.          array[nFound++] = "";
  60.       start = end + 1;
  61.    }
  62.    
  63.    return nFound;
  64. }
  65.  
  66. -- 
  67. Dave Fernandes
  68. Postdoctoral Research Associate
  69. The Ecosystems Center
  70. Marine Biological Laboratory
  71.